#include <sys/types.h>
#include <sys/stat.h>   //mkfifo()
#include <fcntl.h>      //O_WRONLY O_RDONLY
#include <iostream>
#include <pthread.h>
#include <unistd.h>

#define FIFOPATH1 "/home/xbq/dev/test/thread/runing_thread/fifo1"
#define FIFOPATH2 "/home/xbq/dev/test/thread/runing_thread/fifo2"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

using namespace std;

void* thread1 (void*)
{
	int readfd, writefd;
	string str = "nihao\n\r";
	writefd = open(FIFOPATH1, O_WRONLY);
	readfd = open(FIFOPATH2, O_RDONLY);
	
	while (true)
	{
		write(writefd, str.c_str(), str.length());
		cout << "This is in thread1.----->>" << endl;
		sleep(1);
	}
}

void* thread2 (void*)
{
	int readfd, writefd;
	char buff[128];
	readfd = open(FIFOPATH1, O_RDONLY);
	writefd = open(FIFOPATH2, O_WRONLY);

	while (true)
	{
		cout << "This is in thread2." << endl;
		sleep(5);
		cout << read(readfd, buff, 128);
		cout << buff << endl;
	}
}

int main (void)
{
	pthread_t tid1, tid2;
	mkfifo(FIFOPATH1, FILE_MODE);
	mkfifo(FIFOPATH2, FILE_MODE);

	pthread_create(&tid1, NULL, thread1, NULL);
	pthread_create(&tid2, NULL, thread2, NULL);
	pthread_join(tid1, 0);
	pthread_join(tid2, 0);


	return 0;
}

